package com.iterative.system.service;

import com.iterative.common.persistence.HibernateDao;
import com.iterative.common.service.BaseService;

import com.iterative.system.dao.UserRoleDao;
import com.iterative.system.entity.Role;
import com.iterative.system.entity.User;
import com.iterative.system.entity.UserRole;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(readOnly = true)
public class UserRoleService extends BaseService<UserRole, Long> {
    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public HibernateDao<UserRole, Long> getEntityDao() {
        return userRoleDao;
    }

    public List<UserRole> getUserRolesByUserId(long id) {
        return userRoleDao.findBy("userId", id);
    }

    /**
	 * 获取用户拥有角色id集合
	 * 
	 * @param userId
	 * @return 结果集合
	 */
    public List<Long> getRoleIdList(Long id) {
        return userRoleDao.findRoleIds(id);
    }

    /**
	 * 添加修改用户角色
	 * 
	 * @param id
	 * @param oldList
	 * @param newList
	 */
    @Transactional(readOnly = false)
    public void updateUserRole(Long userId, List<Long> oldList,
        List<Long> newList) {
        // 是否删除
        for (int i = 0, j = oldList.size(); i < j; i++) {
            if (!newList.contains(oldList.get(i))) {
                userRoleDao.deleteUR(userId, oldList.get(i));
            }
        }

        // 是否添加
        for (int m = 0, n = newList.size(); m < n; m++) {
            if (!oldList.contains(newList.get(m))) {
                userRoleDao.save(getUserRole(userId, newList.get(m)));
            }
        }
    }
    /**
	 * 构建UserRole
	 * 
	 * @param userId
	 * @param roleId
	 * @return UserRole
	 */
    private UserRole getUserRole(Long userId, Long roleId) {
        UserRole ur = new UserRole();
        //		ur.setUser(new User(userId));
        //		ur.setRole(new Role(roleId));
        ur.setUserId(userId);
        ur.setRoleId(roleId);

        return ur;
    }
}
